var express = require('express');
var pingpp = require('pingpp')('sk_test_mjTW1GHC8Oe10yHKiPvD0088');
var router = express.Router();
var bodyParser = require('body-parser').json({ limit: '100mb' });

var fs = require("fs");
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var util = require('util'); //跨盘移动文件
//config
const Config = require("../util/config");
const Request = require("../util/request");
const Util = require("../util/util");
//upload
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
//qiniu
var qiniu = require("qiniu");

//html>PDF
var pdf = require('capture-pdf');


/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: '静态聊天交互页面' });
});

/**
 * kindedit编辑器
 */
router.get("/kindedit", function(req, res, next) {
    res.render("kindedit", { title: "kindedit" });
})

/**
 * ckedit编辑器
 */
router.get("/ckedit", function(req, res, next) {
    res.render("ckedit", { title: "ckedit" });
})

router.post("/ckupload", multipartMiddleware, function(req, res, next) {
    var _ckNum = req.query.CKEditorFuncNum;
    var _file = req.files.upload;
    var tmpPath = _file.path;
    var type = _file.type;
    var tmp_name = (Date.parse(new Date()) / 1000);
    tmp_name = tmp_name + '' + (Math.round(Math.random() * 9999));
    var extension_name = "";
    //判断文件类型
    switch (type) {
        case 'image/pjpeg':
            extension_name = 'jpg';
            break;
        case 'image/jpeg':
            extension_name = 'jpg';
            break;
        case 'image/gif':
            extension_name = 'gif';
            break;
        case 'image/png':
            extension_name = 'png';
            break;
        case 'image/x-png':
            extension_name = 'png';
            break;
        case 'image/bmp':
            extension_name = 'bmp';
            break;
    }
    var tmp_name = tmp_name + '.' + extension_name;
    var targetPath = 'public/images/ckedit/' + tmp_name;

    //将上传的临时文件移动到指定的目录下
    /*    fs.rename(tmpPath, targetPath , function(err) {
     if (err) {
     throw err;
     }
     //删除临时文件
     fs.unlink(tmpPath, function(){
     if(err) {
     throw err;
     }
     });
     res.end("targetPath");
     });*/
    var readStream = fs.createReadStream(tmpPath);
    var writeStream = fs.createWriteStream(targetPath);

    util.pump(readStream, writeStream, function() {
        fs.unlinkSync(tmpPath);
        targetPath = targetPath.replace(/^public/i, "");
        res.end('<script>window.parent.CKEDITOR.tools.callFunction("' + _ckNum + '","' + targetPath + '","");</script>');
    });
});

/**
 * getimg
 */
router.get('/getimg', function(req, res, next) {
    qiniu.conf.ACCESS_KEY = 'xUv7TvEeWDfH9aOcSZLAANevf6WAgp3iuAKlmV9L';
    qiniu.conf.SECRET_KEY = 's5unctegTsahyGEx3q420q_CTa20WULDIDRfFj7c';
    var key = req.query.key;
    //构建私有空间的链接
    if (key) {
        url = 'http://7xkdj2.com1.z0.glb.clouddn.com/' + key;
        var policy = new qiniu.rs.GetPolicy();
        //生成下载链接url
        var downloadUrl = policy.makeRequest(url);
        //打印下载的url
        console.log(downloadUrl);
        return res.send(downloadUrl);
    } else {
        return res.send("此处应该有默认图片");
    }
});

/**
 * 上传
 */
router.get("/uplodify", function(req, res, next) {
    res.render("uplodify", {
        title: "七牛上传"
    });
});

/**
 * 七牛上传
 */
router.post('/upload', multipartMiddleware, function(req, res, next) {
    //需要填写你的 Access Key 和 Secret Key
    qiniu.conf.ACCESS_KEY = 'xUv7TvEeWDfH9aOcSZLAANevf6WAgp3iuAKlmV9L';
    qiniu.conf.SECRET_KEY = 's5unctegTsahyGEx3q420q_CTa20WULDIDRfFj7c';
    //要上传的空间
    bucket = 'store';
    //上传到七牛后保存的文件名
    key = req.files.imgFile.originalFilename;
    //构建上传策略函数
    function uptoken(bucket, key) {
        var putPolicy = new qiniu.rs.PutPolicy(bucket + ":" + key);
        return putPolicy.token();
    }
    //生成上传 Token
    token = uptoken(bucket, key);
    //要上传文件的本地路径
    filePath = req.files.imgFile.path;
    //构造上传函数
    function uploadFile(uptoken, key, localFile) {
        var extra = new qiniu.io.PutExtra();
        qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
            if (!err) {
                // 上传成功， 处理返回值
                //构建私有空间的链接
                url = 'http://7xkdj2.com1.z0.glb.clouddn.com/' + ret.key;
                var policy = new qiniu.rs.GetPolicy();
                //生成下载链接url
                var downloadUrl = policy.makeRequest(url);
                console.log(ret.hash, ret.key, ret.persistentId);
                return res.send({ error: 0, url: downloadUrl, message: "" });
            } else {
                // 上传失败， 处理返回代码
                console.log(err);
            }
        });
    }
    //调用uploadFile上传
    uploadFile(token, key, filePath);
});
/*ping++*/
router.get("/cart", function(req, res, next) {

    res.render("cart", { title: "cart" });
})

router.post("/order", function(req, res, next) {
    //pingpp.setPrivateKey(_key);
    pingpp.setPrivateKeyPath("public/key.pem");
    pingpp.charges.create({
        order_no: "123456789",
        app: { id: "app_aHaPaT54K4yPDyX9" },
        channel: "alipay_pc_direct",
        amount: 100,
        client_ip: "127.0.0.1",
        currency: "cny",
        subject: "Your Subject",
        body: "Your Body",
        extra: {
            success_url: "http://115.29.79.53:3001/pay",
            enable_anti_phishing_key: false,
            exter_invoke_ip: "127.0.0.1"
        }
    }, function(err, charge) {
        if (err) {
            console.log("::::::::::::error:::::::::::::::::::::::::::::::::" + JSON.stringify(err));
            return res.json(err);
        }
        console.log(":::::::::::::::::::::::::::::::::::::::::::::" + JSON.stringify(charge));
        // YOUR CODE
        res.json(charge);
    });
})

router.get("/pay", function(req, res, next) {
    res.render("/pay", { title: "付款" });
});

/*jsonp*/
router.post("/jsonp", function(req, res, next) {
    var _callback = req.query.jsoncallback;
    console.log(req.body);
    return res.end(_callback + "({\"login\":false})");
})

/**
 *  html?pdf
 */
router.get("/html-pdf", function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    pdf('http://www.163.com', { delay: 5 }).then(buffer => {
        fs.writeFileSync('./public/demo/out.pdf', buffer);
        return res.end(buffer);
    });
})

/**
 * 手机编辑器
 */
router.get("/arteditor", function(req, res, next) {
    //res.header("Access-Control-Allow-Origin", "*");
    res.render('arteditor', { content: 'Express' });
})
/**
 * 手机编辑器 上传图片
 */
router.post("/arteditorupload", multipartMiddleware, function(req, res, next) {
    var _file = req.files.filed;
    console.log(JSON.stringify(_file));
    var tmpPath = _file.path;
    var type = _file.type;
    var tmp_name = (Date.parse(new Date()) / 1000);
    tmp_name = tmp_name + '' + (Math.round(Math.random() * 9999));
    var extension_name = "";
    switch (type) {
        case 'image/pjpeg':
            extension_name = 'jpg';
            break;
        case 'image/jpeg':
            extension_name = 'jpg';
            break;
        case 'image/gif':
            extension_name = 'gif';
            break;
        case 'image/png':
            extension_name = 'png';
            break;
        case 'image/x-png':
            extension_name = 'png';
            break;
        case 'image/bmp':
            extension_name = 'bmp';
            break;
    }
    var tmp_name = tmp_name + '.' + extension_name;
    var targetPath = 'public/images/arteditoredit/' + tmp_name;
    var readStream = fs.createReadStream(tmpPath);
    var writeStream = fs.createWriteStream(targetPath);
    util.pump(readStream, writeStream, function() {
        fs.unlinkSync(tmpPath);
        targetPath = targetPath.replace(/^public/i, "");
        res.json({ "path": targetPath, "success": true });
    });
});

/**
 * spy爬虫
 */
router.get("/spy", function(req, res, next) {
    //采：http://it.cri.cn/
    var scrapy = require('node-scrapy'),
        url = 'https://github.com/strongloop/express',
        selector = '.repository-meta-content'
    scrapy.scrape(url, selector, function(err, data) {
        if (err) return console.error(err)
        console.log(data)
        res.end(data);
    });
});
/**
 * webuploader
 */
router.get("/webuploader", function(req, res, next) {
    res.render("webuploader");
});
/**
 * 手机编辑器 上传图片
 */
router.post("/webuploaderupload", multipartMiddleware, function(req, res, next) {
    var _file = req.files.file;
    console.log(JSON.stringify(req.files));
    var tmpPath = _file.path;
    var type = _file.type;
    var tmp_name = (Date.parse(new Date()) / 1000);
    tmp_name = tmp_name + '' + (Math.round(Math.random() * 9999));
    var extension_name = "";
    switch (type) {
        case 'image/pjpeg':
            extension_name = 'jpg';
            break;
        case 'image/jpeg':
            extension_name = 'jpg';
            break;
        case 'image/gif':
            extension_name = 'gif';
            break;
        case 'image/png':
            extension_name = 'png';
            break;
        case 'image/x-png':
            extension_name = 'png';
            break;
        case 'image/bmp':
            extension_name = 'bmp';
            break;
    }
    var tmp_name = tmp_name + '.' + extension_name;
    var targetPath = 'public/images/webuploader/' + tmp_name;
    var readStream = fs.createReadStream(tmpPath);
    var writeStream = fs.createWriteStream(targetPath);
    util.pump(readStream, writeStream, function() {
        fs.unlinkSync(tmpPath);
        targetPath = targetPath.replace(/^public/i, "");
        res.json({ "path": targetPath, "success": true });
    });
});

/**
 * websocket
 */
router.get("/ws", (req, res, next) => {
    var countdown;
    clearInterval(countdown);
    var end = 600;
    countdown = setInterval(function() {
        if (end < 0) {
            clearInterval(countdown);
            end = 600;
        }
        end--;
    }, 1000)
    res.render("ws", {
        endtime: end
    });
})

/**
 * fs
 */
router.get("/fs", (req, res, next) => {
    const fs = require('fs');
    fs.readFile('\public\\doc\\test.txt', (err, data) => {
        if (err) throw err;
        console.log(data);
        console.log(data.toString());
    });
})


router.get("/vs", (req, res, next) => {
    return res.render("vs");
})

/**
 * @param m {图片路径}
 */
router.get("/youtu", (req, res, next) => {
    var tencentyoutuyun = require('../youtu_sdk');
    var conf = tencentyoutuyun.conf;
    var youtu = tencentyoutuyun.youtu;

    // 设置开发者和应用信息, 请填写你在开放平台
    var appid = Config.youtu_appid;
    var secretId = Config.youtu_secretId;
    var secretKey = Config.youtu_secretKey;
    var userid = Config.youtu_userid; //接入业务自行定义的用户id，用于唯一标识一个用户
    conf.setAppInfo(appid, secretId, secretKey, userid, 0)
    // youtu.namecardocr('http://opentest.youtu.qq.com/content/img/product/ocr/ocr_common01.jpg',false, function(data){
    //    res.send("imagetag:" + JSON.stringify(data));
    // });
    // var fs = require("fs");
    // var imageBuf = fs.readFileSync("D:\\nodejs\\node-niu\\public\\files\\ocr_common01.jpg");
    // console.log(imageBuf.toString("base64"));
    youtu.generalocr("http://opentest.youtu.qq.com/content/img/product/ocr/ocr_common01.jpg", function(data) {
        res.send("generalocr:" + JSON.stringify(data));
    });
})


//csrf
router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});


router.get("/OCRImg", bodyParser, (req, res, next) => {
    // let _ret = {"result":{"resultCode":0,"resultMessage":""},"entity":{"errorcode":0,"errormsg":"OK","items":[],"session_id":""}};
    let imagePath = "/9j/4AAQ2Q==";
    let _ret = Util.saveImg(imagePath);
    return res.send("_ret:" + _ret);
})

//图片识别
router.post("/OCRImg", bodyParser, (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    var https = require("https");
    var _appid = Config.youtu_appid;
    var _sign = Util.buildEncryptParam();

    var param = "";
    var imagePath = req.body.m;
    //保存图片
    Util.saveImg(imagePath);
    if (!imagePath) {
        return res.end("参数中错误.eg:" + "?m=http://opentest.youtu.qq.com/content/img/product/ocr/ocr_common01.jpg")
    }
    if (imagePath.indexOf("http") > -1) {
        param = JSON.stringify({
            url: imagePath,
            app_id: Config.youtu_appid
        });
    } else if (imagePath.indexOf("http") == -1 && /\.jpg|\.gif|\.png/.test(imagePath)) {
        try {
            var _data = fs.readFileSync(imagePath).toString('base64');
        } catch (e) {
            console.log("read fail")
            return;
        }
        if (_data == null) {
            console.log(' not exists or params error');
            return;
        };
        param = JSON.stringify({
            app_id: _appid,
            image: _data.toString('base64'),
        });
    } else {
        // console.log("base64:"+imagePath);
        param = JSON.stringify({
            app_id: _appid,
            image: imagePath
        });
    }
    var headers = {
        'Content-Type': 'text/json',
        'Content-Length': param.length,
        'Authorization': _sign
    };
    var options = {
        hostname: 'api.youtu.qq.com',
        path: '/youtu/ocrapi/generalocr',
        method: 'POST',
        headers: headers
    };
    console.log("options:" + JSON.stringify(options));
    var _body = '';
    var _req = https.request(options, (ret) => {
        ret.setEncoding("utf8");
        ret.on('data', (chunk) => {
                _body += chunk;
            })
            .on('end', () => {
                let _ret = {
                    "result": {
                        "resultCode": 0,
                        "resultMessage": ""
                    }
                };
                try {
                    _body = JSON.parse(_body)
                } catch (e) {
                    console.log("parse e:" + e);
                }
                console.log(`识别结果<==(${new Date().toLocaleString()}):${JSON.stringify(_body)}`);
                _ret.entity = _body;
                res.json(_ret);
            })
            .on('error', (e) => {
                console.error(e);
                let _ret = {
                    "result": {
                        "resultCode": 0,
                        "resultMessage": e
                    },
                    "entity": e
                }
                res.json(_ret);
            });
    });
    _req.write(param);
})

/*
 * 按行读取文件
 */
router.get("/readline", bodyParser, (req, res, next) => {
    const fs = require('fs');
    var readline = require('readline');
    var fRead = fs.createReadStream(__dirname + '/../public\/doc\/log\/log1.txt');
    var fWrite = fs.createWriteStream(__dirname + '/../public\/doc\/log\/log2.txt');
    var enableWriteIndex = true;
    fRead.on('end', () => {
        console.log('end');
        enableWriteIndex = false;
    });
    var objReadline = readline.createInterface({
        input: fRead,
        output: fWrite,
        terminal: true
    });
    var index = 1;
    fWrite.write('line' + index.toString() + ':');
    objReadline.on('line', (line) => {
        console.log(index, line);
        if (enableWriteIndex) {
            // 由于readline::output是先写入后调用的on('line')事件，  
            // 所以已经读取文件完毕时就不需要再写行号了... sodino.com  
            index++;
            var tmp = 'line' + index.toString() + ':';
            fWrite.write(tmp);
        }
    });
    objReadline.on('close', () => {
        console.log('readline close...');
    });

});


/**
 * send mail
 */
router.get("/mail", (req, res, next) => {
    Util.sendMail('690040322@qq.com', '主题', '内容', function(err) {
        if (err) {
            res.json({ 'msg': '发送错误' + err })
        }
        C
        res.json({ 'msg': '发送成功' + err })
    })
})



module.exports = router;